package com.lgl.scs.system.interceptor.shiro;

import com.lgl.scsapi.system.model.AppUser;
import com.lgl.scsapi.util.utils.Constants;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

/**
 * 权限验证
 */
public class ShiroRealm extends AuthorizingRealm {

	/*
	 * 登录信息和用户验证信息验证(non-Javadoc)
	 * @see
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		/*String username = (String)token.getPrincipal();  				//得到用户名
		String password = new String((char[])token.getCredentials()); 	//得到密码
		//char[] password = (char[])token.getCredentials();
		if(null != username && null != password){
	    	return new SimpleAuthenticationInfo(username, password, getName());
	    }
		return null;*/
		UsernamePasswordToken userToken = (UsernamePasswordToken)token;
		String hashPassword = new SimpleHash(Constants.ALGORITHM_NAME,userToken.getPassword(), Constants.SHIRO_SALT,Constants.HASH_ITERATIONS).toHex();
		if(userToken == null) {
			throw new UnknownAccountException("账号或密码不正确");
		}
		AppUser tokenUser = new AppUser(userToken.getUsername(), hashPassword);
	    return new SimpleAuthenticationInfo(tokenUser, hashPassword, ByteSource.Util.bytes(Constants.SHIRO_SALT),getName());
	}
	
	/*
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用,负责在应用程序中决定用户的访问控制的方法(non-Javadoc)
	 * @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String userName = (String) principals.getPrimaryPrincipal();
		//User user = userService.findByAccount(username);
		if(null == userName){
			return null;
		}
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		/*for (SysRole role : user.getRoleList()) {
			authorizationInfo.addRole(role.getRole());  // 添加角色
			for (SysPermission permission : role.getPermissions()) {
				authorizationInfo.addStringPermission(permission.getPermission());  // 添加具体权限
			}
		}*/
		return authorizationInfo;
	}
	@Override
	public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
		HashedCredentialsMatcher shaCredentialsMatcher = new HashedCredentialsMatcher();
		shaCredentialsMatcher.setHashAlgorithmName(Constants.ALGORITHM_NAME);
		shaCredentialsMatcher.setHashIterations(Constants.HASH_ITERATIONS);
		super.setCredentialsMatcher(shaCredentialsMatcher);
	}
}